import { __private, director, sys } from "cc";
import { EDITOR } from "cc/env";
import { aaEvent } from "../common/Enums";

interface LocaleData {
    [key: string]: string;
}

interface Locales {
    [key: string]: LocaleData;
}

class I18n {
    private defaultLocale: string = 'en';
    private localizationData: Locales = {};
    private debug = null;
    _local = null;
    
    getCurrentLocale(){
        let local = this.debug?this.debug:sys.language;
        const msg = "Current Language == "+local;
        console.log(EDITOR?'':'\x1b[33m%s\x1b[0m',msg);
        local= local.slice(0,2)||this.defaultLocale;
        return local;
    }

    constructor () {
        // this._local = this.getCurrentLocale();
    }
    get locale(){
        return this._local;
    }

    set locale (locale: string) {
        this._local = locale;
        this.updateLocal();
    }

    loadLocaleData (locale: string, data: LocaleData) {
        this.localizationData[locale] = data;
    }
    updateLocal() {
        director.emit(aaEvent.updateLocal);
    }

    t (key: any, obj?:string): any {
        const win: any = window;
        let data = win.languages[this._local];
        if(!data){
            return key;
        }
        if(obj){
            data = data[obj];
            if (!data) {
                return key;
            }
            return data[key] || key;
        }
        if(typeof key =="string"){
            const searcher = key.split('.');
            for (let i = 0; i < searcher.length; i++) {
                data = data[searcher[i]];
                if (!data) {
                    return key;
                }
            }
            return data || key;
        }
        return key;
       
    }
}
const i18n = new I18n;

export default i18n;
